package demo.dao;

import jdbc.DBUtil;
import jdbc.Userinfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserMapper {
    public int insert(Userinfo userinfo){
        try (Connection connection= DBUtil.getConnection();){
            PreparedStatement ps=connection.prepareStatement("INSERT INTO userinfo(username,password,nickname,age) " +
                    "VALUES (?,?,?,?)");
            ps.setString(1,userinfo.getUsername());
            ps.setString(2,userinfo.getNickname());
            ps.setString(3,userinfo.getPassword());
            ps.setInt(4,userinfo.getAge());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public Userinfo findUsername(String username) {
        try (Connection connection = DBUtil.getConnection();) {
            PreparedStatement ps = connection.prepareStatement(
                    "SELECT username,password,nickname,age " +
                            "FROM userinfo " +
                            "WHERE username= ? ");
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                Userinfo userinfo = new Userinfo();
                userinfo.setUsername(rs.getString("username"));
                userinfo.setPassword(rs.getString("password"));
                userinfo.setNickname(rs.getString("nickname"));
                userinfo.setAge(rs.getInt("age"));
                return userinfo;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    }

